# %% Global variables ---
RESP.SHAPES <- c(21, 19, 0, 8, 20) # Shapes for CR, PR, SD, PD, NE
# RESP.SHAPES <- c(22, 19, 0, 8, 20)  # CR can be filled with color

RESP.LEVELS <- c("CR", "PR", "SD", "PD", "NE")

RESP.COLORS <- c(
  "CR" = "#F6CA15",
  "PR" = "#64A83D",
  "SD" = "#8DB5CE",
  "PD" = "#ED5A9E",
  "NE" = "#7E6875"
)

# Dose levels (for 2025/9/6)
DOSE.LEVELS <- c("0.6", "1.2", "1.6", "2.0", "2.4", "3.0", "3.6")

DOSE.COLORS <- c(
  "0.6" = "#9E6762",
  "1.2" = "#E6D656",
  "1.6" = "#637A50",
  "2.0" = "#C693BE",
  "2.4" = "#6991CD",
  "3.0" = "#A49D4B",
  "3.6" = "#EE4E21"
)


# %% Help functions ----

#' Translate the Chinese tumor into English
#'
#' @param tumor.cn: a list of tumor of Chinese
#' @param type: 0 is default, 1 - 输卵管癌也属于OC
#' @return: a list of tumor of English
tumor2en <- function(tumor.cn, type = 0) {
  # Create a mapping dictionary (for 2025/9/6)
  tumor.map <- c(
    "宫颈癌" = "CC",
    "胰腺癌" = "PDAC",
    "尿路上皮癌" = "UC",
    "卵巢癌" = "OC",
    "鼻咽癌" = "NPC",
    "头颈鳞癌" = "HNSCC",
    "输卵管癌" = "FTC",
    "前列腺癌" = "PC",
    "结直肠癌" = "CRC"
  )

  if (type == 1) {
    tumor.map["输卵管癌"] <- "OC"
  }

  # Use str_replace_all() function to replace all Chinese tumors with English
  tumor.en <- str_replace_all(tumor.cn, tumor.map)

  return(tumor.en)
}

#' Read patients information from manual Excel file [XNW28 sheet]
#'
#' @param path: the directory of the data file
#' @param data_file: the data file name
#' @return: a data frame of patients information
read_patient_info <- function(
  path = "D:/Work/TF/Ph1",
  datafile = "XNW28012_SubjectList.xlsx"
) {
  data.filename <- paste0(path, "/", datafile)

  # 读取指定的Excel文件中的数据，并进行初步处理
  pts.info <- read_xlsx(
    data.filename,
    sheet = "XNW28",
    range = cell_cols("A:X"),
    na = "/", # 缺失值用斜杠表示, 主要是TF列
    col_types = c(
      "text", # A - Patient
      "text", # B - CurrentState
      "text", # C - Sex
      "numeric", # D - Age
      "text", # E - Tumor
      "numeric", # F - TF
      "numeric", # G - Dose
      "date", # H - C1D1
      "numeric", # I - Current cycle
      "date", # J - Last Radio date
      "text", # K - BOR
      "text", # L - Last Evaluation note (-)
      "date", # M - End date
      "text", # N - End reason
      "logical", # O - isDoseEsca: 1 for dose escalation, 0 for dose expansion
      "logical", # P - isDoseReductio: 1 for dose reduction, 0 for non-reduction
      "date", # Q - Next vist date (-)
      "date", # R - Next radio date (-)
      "numeric", # S - Lines of history anti-tumor therapy
      "numeric", # T - 是否使用过伊立替康
      "numeric", # U - 是否使用过免疫治疗
      "text", # V - 肿瘤治疗史描述 (-)
      "text", # W - 是否铂耐药
      "numeric" # X - 转移器官数量
    )
  )

  # 筛选出患者数据，剔除缺失值
  pts.info <- pts.info |>
    filter(!is.na(Patient)) |>
    filter(!is.na(C1D1)) |> # 没有给药【无C1D1】
    filter(!is.na(Dose)) # 没有剂量组

  pts.info <- pts.info |>
    # Delete unnecessary columns
    select(-LastEvaluationNote, -NextVisit, -NextRadio, -TumorHistory) |>
    mutate(
      C1D1 = as_date(C1D1),
      EndDate = as_date(EndDate),
      LastRadio = as_date(LastRadio),
      Dose = sprintf("%0.1f", Dose) # 2 -> 2.0
    ) |>
    mutate(
      TumorCN = Tumor,
      Tumor = tumor2en(Tumor),
      CurrentState = factor(ifelse(
        CurrentState == "治疗",
        "Ongoing",
        "Discontinued"
      )),
      Sex = factor(ifelse(Sex == "男", "Male", "Female")),
      Dose = factor(Dose, levels = DOSE.LEVELS),
      BOR = factor(BOR, levels = RESP.LEVELS)
    )

  return(pts.info)
}


#' Read target lesion information from manual Excel file [TargetLesion sheet]
#'
#' @param path: the directory of the data file
#' @param data_file: the data file name
#' @return: a data frame of target lesion information
read_targetlesion_info <- function(
  path = "D:/Work/TF/Ph1",
  datafile = "XNW28012_SubjectList.xlsx"
) {
  data.filename <- paste0(path, "/", datafile)

  # recist_df means response results
  recist <- read_xlsx(
    data.filename,
    sheet = "TargetLesion",
    range = cell_cols("A:E"),
    na = "NA",
    col_types = c("text", "date", "numeric", "numeric", "text")
  )

  # 确保 'Date.eva' 列是日期格式
  recist$Date.eva <- as_date(recist$Date.eva)

  recist$RECIST <- factor(recist$RECIST, levels = RESP.LEVELS)

  return(recist)
}


#' Plot filter function
#'
#' @param tumor: PDAC, OC, CC ...
#' @param dose: 0.6, 1.2, 2.0, 2.4, 3.0 or 3.6
#' @param phase: dose-escalation (esca) or dose-expansion (expn)
#' @param addition: 0 for no addition selection, 1 for addition selection
#' @return: a data frame of selected patients' IDs
filter_plotset <- function(
  tumor = c("PDAC", "OC", "CC", "CRC", "PC", "HNSCC", "NPC", "FTC", "UC"),
  dose = c("0.6", "1.2", "2.0", "2.4", "3.0", "3.6"),
  phase = "all",
  addition = 0
) {
  phase <- toupper(phase)
  tumor <- toupper(tumor)

  # 首先筛选研究阶段
  # 1: dose-escalation (esca)
  # 2: dose-expansion (expn)
  if (phase == "ESCA" || phase == "ESCALATION" || phase == 1) {
    plot.set <- filter(patient.info, isDoseEsca == TRUE)
  } else if (
    phase == "EXPANSION" || phase == "EXP" || phase == "EXPN" || phase == 2
  ) {
    plot.set <- filter(patient.info, isDoseEsca == FALSE)
  } else if (phase == "ALL") {
    plot.set <- patient.info
  }

  # 筛选肿瘤类型和剂量组
  plot.set <- plot.set |>
    filter(Tumor %in% tumor, Dose %in% dose)

  # 如果还有进一步的筛选，就返回全部的数据，否则只返回患者ID
  if (addition == 0) {
    plot.set <- plot.set |>
      select(Patient)
  }

  return(plot.set)
}
